package com.hakim.wfb.platform.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 静态工具类
 *
 * @author
 *
 */
public class StaticTool {

    private static Logger logger = LoggerFactory.getLogger(StaticTool.class);

    public static final SimpleDateFormat shortSDF = new SimpleDateFormat(
            "yyyy-MM-dd");
    public static final SimpleDateFormat longSDF = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat longSDFNoSecond = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm");
    public static final DecimalFormat df8 = new DecimalFormat("#0.00000000");
    public static final DecimalFormat df7 = new DecimalFormat("#0.0000000");
    public static final DecimalFormat df6 = new DecimalFormat("#0.000000");
    public static final DecimalFormat df5 = new DecimalFormat("#0.00000");
    public static final DecimalFormat df4 = new DecimalFormat("#0.0000");
    public static final DecimalFormat df3 = new DecimalFormat("#0.000");
    public static final DecimalFormat df2 = new DecimalFormat("#0.00");
    public static final DecimalFormat df1 = new DecimalFormat("#0.0");
    public static final DecimalFormat df8No0 = new DecimalFormat("#.########");
    public static final DecimalFormat df2_bai = new DecimalFormat("##.00%");

    /**
     * 判断是否为数字
     * @param str
     * @return
     */
    public  static boolean isNum(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得真实ip
     *
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 从request中获取请求参数
     *
     * @param request
     * @return Map
     *
     */
    public static Map getRequestParams(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String key = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            key = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(key, value);
        }
        return returnMap;
    }

    /**
     * 验证是否邮件地址
     *
     * @param email
     * @return
     * @throws Exception
     */
    public static boolean checkEmail(String email) {
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        return matcher.matches();
    }

    /**
     * 验证是否手机号码
     *
     * @param mobilePhone
     * @return
     * @throws Exception
     */
    public static boolean checkMobilePhone(String mobilePhone) {
        String check = "^(13|15|17|18)\\d{9}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(mobilePhone);
        return matcher.matches();
    }

    /**
     * 验证是否身份证号码
     *
     * @param personCardNo
     * @return
     * @throws Exception
     */
    public static boolean checkPersonCardNo(String personCardNo) {

        // String check18 = "^\\d{15}|\\d{18}$";
        String check18 = "(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9x-xX-X])";
        // String check15 =
        // "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{4}$";
        Pattern regex = Pattern.compile(check18);
        Matcher matcher = regex.matcher(personCardNo);

        return matcher.matches();
    }

    /**
     * 输出JSON
     *
     * @param response
     * @param resultMap
     * @param resultMap2
     *            add by caochong
     */
//    public static void outJson(HttpServletResponse response,
//                               Map<String, Object> reqeustMap, String json) {
//
//        try {
//            PrintWriter pw;
//            // 是否跨域，跨域要带上jsonCallBack
//            if ("1".equals(ZJZCPropertyUtils.getProperty("jsonp"))) {
//                json = reqeustMap.get(CommonConstant.JSONCALLBACK) + "(" + json
//                        + ")";
//            }
//            response.setCharacterEncoding(ZJZCPropertyUtils
//                    .getProperty("encode"));
//            // response.setHeader("Access-Control-Allow-Origin", "*");
//            // response.setHeader("P3P","CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
//            pw = response.getWriter();
//            pw.write(json);
//        } catch (IOException e) {
//            logger.error("", e);
//        }
//    }

    /**
     * 输出JSON
     *
     * @param response
     * @param resultMap
     * @param resultMap2
     *            add by caochong
     */
//    public static void outJson(HttpServletResponse response,
//                               Map<String, Object> reqeustMap, Map resultMap) {
//
//        try {
//            PrintWriter pw;
//            JSONObject obj = new JSONObject(resultMap);
//            String json = "";
//            // 是否跨域，跨域要带上jsonCallBack
//            if ("1".equals(ZJZCPropertyUtils.getProperty("jsonp"))) {
//                json = reqeustMap.get(CommonConstant.JSONCALLBACK) + "(" + obj.toJSONString()
//                        + ")";
//            } else {
//                json = obj.toJSONString();
//            }
//            response.setCharacterEncoding(ZJZCPropertyUtils
//                    .getProperty("encode"));
//            // response.setHeader("Access-Control-Allow-Origin", "*");
//            // response.setHeader("P3P","CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
//            pw = response.getWriter();
//            pw.write(json);
//        } catch (IOException e) {
//            logger.error("", e);
//        }
//
//    }

    /**
     * post 方式直接 json返回
     * @param response
     * @param json
     */
//    public static void outJson(HttpServletResponse response,String json){
//        try {
//            PrintWriter pw;
//            response.setCharacterEncoding(ZJZCPropertyUtils.getProperty("encode"));
//            //response.setContentType("application/json;charset=UTF-8");
//            response.setContentType("text/html");
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            pw = response.getWriter();
//            pw.write(json);
//        } catch (IOException e) {
//            logger.error("", e);
//        }
//    }

    /**
     * JSON转Map
     *
     * @param json
     *            add by caochong
     */
    public static Map<String, Object> parseJSON2Map(JSONObject json) {
        Map<String, Object> map = new HashMap<String, Object>();

        // 最外层解析
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            // 如果内层还是数组的话，继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<Object> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = (JSONObject) it.next();
                    list.add(parseJSON2Map(json2));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    /**
     * 生成通行证 随机数+用户ID+来源+时间戳
     *
     * @param sn
     *            用户ID
     * @param source
     *            用户请求来源 add by caochong
     * @return
     */
//    public static String genPassPort(Object sn, String source) {
//        // 得到随机数
//        double rm = Math.random();
//        long num = (long) (rm * 100000000);
//        // 封装加密前字符串 随机数+用户ID+来源+时间戳
//        String beforeStr = num + "-" + sn + "-" + source + "-"
//                + new Date().getTime();
//        return DesUtils.getInstance().encrypt(beforeStr);
//    }

    /**
     * 从请求参数的MAP中获得字符串值
     *
     * @param requestParams
     * @param key
     * @return
     */
    public static String getRequestParamStringFromMap(Map requestParams,
                                                      String key) {
        String res = null;
        if (requestParams == null) {
            return "";
        }
        return requestParams.get(key) == null ? "" : requestParams.get(key)
                .toString();
    }

    /**
     * 从shiro session中获得字符串值
     *
     * @param session
     * @param key
     * @returns
     */
    public static String getSessionString(HttpSession session, String key) {
        //String res = null;
        return session.getAttribute(key) == null ? "" : session.getAttribute(
                key).toString();
    }

    /**
     * 从shiro session中获得字符串值
     *
     * @param session
     * @param key
     * @return
     */
//    public static String getSessionString(Session session, String key) {
//        String res = null;
//        return session.getAttribute(key) == null ? "" : session.getAttribute(
//                key).toString();
//    }

    /**
     * 验证来源有效性
     *
     * @param request
     * @param source
     * @return
     */
//    public static boolean checkSourceIsTrue(HttpServletRequest request,
//                                            String source) {
//        source = source.replace(";", "");
//        if (StringUtils.isBlank(source)) {
//            return false;
//        }
//        // 简单版本,后面加入IP限制
//        return CommonConstant.SOURCELIST.contains(source);
//    }

    /**
     * 将字符加入遮掩码
     *
     * @param str
     *            要遮掩的字符
     * @param front
     *            从前面保留几位不遮掩
     * @param back
     *            从后面保留几位不遮掩
     * @return
     */
    public static Object covertString(String str, int front, int back) {
        if (StringUtils.isBlank(str) || str.length() < (front + back)) {
            return str;
        }

        int frontNum = (front <= 0 ? 0 : front - 1);
        int backNum = (back < 0 ? 0 : back);

        StringBuffer sb = new StringBuffer();
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (i <= frontNum) {
                sb.append(arr[i]);
            } else if (i >= arr.length - back) {
                sb.append(arr[i]);
            } else {
                sb.append("*");
            }
        }
        return sb.toString();
    }

    /**
     * 字符转换成unicode
     *
     * @param str
     * @return
     */
    public static String covertStringToUniCode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>> 8); // 取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); // 取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
        }
        return (new String(sb));
    }

    /**
     * unicode转换成字符
     *
     * @param str
     * @return
     */
    public static String coverUnicodeToString(String str) {
        str = (str == null ? "" : str);
        if (str.indexOf("\\u") == -1)// 如果不是unicode码则原样返回
            return str;
        StringBuffer sb = new StringBuffer(1000);
        for (int i = 0; i < str.length() - 6;) {
            String strTemp = str.substring(i, i + 6);
            String value = strTemp.substring(2);
            int c = 0;
            for (int j = 0; j < value.length(); j++) {
                char tempChar = value.charAt(j);
                int t = 0;
                switch (tempChar) {
                    case 'a':
                        t = 10;
                        break;
                    case 'b':
                        t = 11;
                        break;
                    case 'c':
                        t = 12;
                        break;
                    case 'd':
                        t = 13;
                        break;
                    case 'e':
                        t = 14;
                        break;
                    case 'f':
                        t = 15;
                        break;
                    default:
                        t = tempChar - 48;
                        break;
                }

                c += t * ((int) Math.pow(16, (value.length() - j - 1)));
            }
            sb.append((char) c);
            i = i + 6;
        }
        return sb.toString();
    }

    /**
     * 将字符中间转换成星号
     *
     * @param nickName
     * @return
     */
    public static String formatStringToStar(String nickName) {
        if (StringUtils.isNotBlank(nickName)) {
            StringBuffer sb = new StringBuffer();
            char[] arr = nickName.toCharArray();
            if (arr.length == 1) {
                return nickName + "**";
            }
            if (arr.length == 2) {
                return nickName + "*";
            } else {
                for (int i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        sb.append(arr[i]);
                    } else if (i == arr.length - 1 && i != 0) {
                        sb.append(arr[i]);
                    } else {
                        sb.append("*");
                    }
                }
                return sb.toString();
            }
        } else {
            return "";
        }
    }

    /**
     * formatStrToStarWithHeadAndTailNums. headNum + tailNum < length
     *
     * @param str
     *            源字符串
     * @param headNum
     *            >0 字符串首几位不用*转化
     * @param tailNum
     *            >0 字符串后几位不用*转化
     * @return
     */
    public static String formatStrToStarWithHeadAndTailNums(String str,
                                                            int headNum, int tailNum) {

        String resultStr = null;
        // 如果字符串长度 大于 首尾保留留长度之和 则对字符串进行*替换, 否则返回原支付串
        if (StringUtils.isNotBlank(str) && str.length() > (headNum + tailNum)
                && headNum > -1 && tailNum > -1) {
            int startNum = str.length() - headNum - tailNum;
            String str1 = str.substring(0, headNum);
            String str2 = StringUtils.rightPad("", startNum, "*");
            String str3 = str.substring(str.length() - tailNum, str.length());
            return str1 + str2 + str3;
        } else {
            resultStr = str;
        }

        return resultStr;
    }

    /**
     *  获得session中的验证码字符
     * @param request
     * @return
     */
    public static  String getValidCodeForHttpSession(HttpServletRequest request) {
        if(request.getSession().getAttribute(SessionNames.VERIFY_CODE)!=null){
            return (String)request.getSession().getAttribute(SessionNames.VERIFY_CODE);
        }else{
            return "no verify code";
        }
    }

    /**
     * 获得服务地址
     * @param request
     * @return
     */
    public static String getServerSiteAddrress(HttpServletRequest request) {
        String serverAddr = request.getRequestURL().toString().replace(request.getRequestURI(), "")+request.getContextPath();
        return serverAddr;
    }

}

